﻿using CodeFirst;
using IRepository;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using ModelDto;
using System.Collections.Generic;
using System.Data.Common;
using System.Data;
using System.Linq.Expressions;
using System.Transactions;
using Model;
using System.Collections;
using Microsoft.Data.SqlClient;
using EFCore.BulkExtensions;
namespace Repository
{
    /// <summary>
    /// 通用仓储接口实现
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    public class BaseRepository<T> : IBaseRepository<T> where T : class
    {

        protected readonly MyDbContext _dbContext;
        //protected readonly DbConnectionFactory _writecontext;

        protected readonly DbSet<T> _dbSet;


        public BaseRepository(MyDbContext _readcontext)

        {
            this._dbContext = _readcontext;
            //_readcontext = new DbConnectionFactory(options, true);

            //_writecontext = new DbConnectionFactory(options, false);


            this._dbSet = _readcontext.Set<T>();

        }
        /// <summary>
        /// 级联更新主表和子表
        /// </summary>
        /// <typeparam name="TPrincipal">主表实体类型</typeparam>
        /// <typeparam name="TDependent">子表实体类型</typeparam>
        /// <typeparam name="TPrincipalKey">主表主键类型</typeparam>
        /// <typeparam name="TDependentKey">子表主键类型</typeparam>
        /// <param name="updatedPrincipal">需要更新的主表实体对象，包含主表和子表的更新数据</param>
        /// <param name="dependentNavigationProperty">导航属性的拉姆达,如f=>f.item</param>
        /// <param name="dependentKeySelector">子表主键的拉姆达</param>
        /// <param name="principalKeySelector">主表主键拉姆达</param>
        public void UpdateWithChildren<TPrincipal, TDependent, TPrincipalKey, TDependentKey>(
            TPrincipal updatedPrincipal,
            Expression<Func<TPrincipal, ICollection<TDependent>>> dependentNavigationProperty,
            Func<TDependent, TDependentKey> dependentKeySelector,
            Func<TPrincipal, TPrincipalKey> principalKeySelector)
            where TPrincipal : class
            where TDependent : class
        {
            // 预编译导航属性表达式
            var compiledNavigationProperty = dependentNavigationProperty.Compile();

            // 1. 加载数据库中现有的主实体及其子实体
            var existingPrincipal = _dbContext.Set<TPrincipal>()
                .Include(dependentNavigationProperty)
                .FirstOrDefault(principal => EqualityComparer<TPrincipalKey>.Default.Equals(principalKeySelector(principal), principalKeySelector(updatedPrincipal)));

            if (existingPrincipal == null)
            {
                // 如果数据库中不存在主实体，则直接添加
                _dbContext.Set<TPrincipal>().Add(updatedPrincipal);
            }
            else
            {
                // 2. 更新主实体的属性
                var principalEntry = _dbContext.Entry(existingPrincipal);
                principalEntry.CurrentValues.SetValues(updatedPrincipal);

                // 3. 处理子实体
                var existingDependents = compiledNavigationProperty(existingPrincipal);
                var updatedDependents = compiledNavigationProperty(updatedPrincipal);
                // 创建一个字典，用于快速查找传入的子实体
                var updatedDependentsDict = updatedDependents.ToDictionary(dependentKeySelector);

                // 遍历数据库中现有的子实体
                foreach (var existingDependent in existingDependents.ToList())
                {
                    var key = dependentKeySelector(existingDependent);
                    if (updatedDependentsDict.TryGetValue(key, out var updatedDependent))
                    {
                        // 如果传入的子实体中存在该子实体，则更新其属性
                        var dependentEntry = _dbContext.Entry(existingDependent);
                        dependentEntry.CurrentValues.SetValues(updatedDependent);
                        // 从字典中移除，避免后续重复处理
                        updatedDependentsDict.Remove(key);
                    }
                    else
                    {
                        // 如果传入的子实体中不存在该子实体，则删除数据库中的子实体
                        _dbContext.Set<TDependent>().Remove(existingDependent);
                    }
                }

                // 4. 添加传入的子实体中不存在于数据库的子实体
                foreach (var newDependent in updatedDependentsDict.Values)
                {
                    _dbContext.Set<TDependent>().Add(newDependent);
                }
            }

            // 5. 保存更改
            _dbContext.SaveChanges();
        }
        public void BeginTransaction()
        {
            if (_dbContext.Database.CurrentTransaction == null)
            {
                _dbContext.Database.BeginTransaction();
            }
        }
        public void Commit()
        {
            var transaction = this._dbContext.Database.CurrentTransaction;
            if (transaction != null)
            {
                try
                {
                    transaction.Commit();
                }
                catch (Exception)
                {
                    transaction.Rollback();
                    throw;
                }
            }
        }

        public void Rollback()
        {
            _dbContext.Database.CurrentTransaction?.Rollback();
        }

        public int SaveChanges()
        {
            return _dbContext.SaveChanges();
        }
        public async Task<int> SaveChangesAsync()
        {
            return await _dbContext.SaveChangesAsync();
        }


        public IQueryable<T> Entities
        {
            get { return _dbSet.AsNoTracking(); }
        }

        public IQueryable<T> TrackEntities
        {
            get { return _dbSet; }
        }

        public T Add(T entity, bool isSave = true)
        {

            _dbSet.Add(entity);
            if (isSave)
            {
                SaveChanges();
            }
            return entity;
        }

        public async Task<T> AddAsync(T entity, bool isSave = true)
        {
            await _dbSet.AddAsync(entity);
            if (isSave)
            {
                await SaveChangesAsync();
            }
            return entity;
        }

        public void AddRange(IEnumerable<T> entitys, bool isSave = true)
        {
            _dbSet.AddRange(entitys);
            if (isSave)
            {
                SaveChanges();
            }
        }

        public void Delete(T entity, bool isSave = true)
        {
            this._dbSet.Remove(entity);
            if (isSave)
            {
                this.SaveChanges();
            }
        }

        public void Delete(bool isSave = true, params T[] entitys)
        {
            this._dbSet.RemoveRange(entitys);
            if (isSave)
            {
                this.SaveChanges();
            }
        }
        // 批量插入
        public async Task<int> BatchInsertAsync(IList<T> entities)
        {
            await _dbContext.BulkInsertAsync(entities);
            return SaveChanges();
        }

        // 批量更新
        public async Task<int> BatchUpdateAsync(IList<T> entities)
        {
            await _dbContext.BulkUpdateAsync(entities);
            return SaveChanges();
        }

        // 批量删除
        public async Task<int> BatchDeleteAsync(IList<T> entities)
        {
            await _dbContext.BulkDeleteAsync(entities);
            return SaveChanges();
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns>-1 || 1</returns>
        public async Task<int> DelAsync(object id)
        {
            var result = await _dbSet.FindAsync(id);
            if (result == null) return -1;
            _dbSet.Remove(result);
            return SaveChanges();
        }

        public void Delete(Expression<Func<T, bool>> @where, bool isSave = true)
        {
            T[] entitys = this._dbSet.Where(@where).ToArray();
            if (entitys.Length > 0)
            {
                this._dbSet.RemoveRange(entitys);
            }
            if (isSave)
            {
                this.SaveChanges();
            }
        }

        public async Task<int> UpdateAsync(T entity)
        {
            var en = _dbContext.Entry(entity);
            if (en.State == EntityState.Detached) en.State = EntityState.Modified;
            return await Task.Run(SaveChangesAsync);
        }

        public int Update(T entity)
        {

            var entry = _dbContext.Entry(entity);
            if (entry.State == EntityState.Detached)
            {
                entry.State = EntityState.Modified;
            }
            var da = SaveChanges();
            return da;
        }
        public void Update(params T[] entitys)
        {
            var entry = this._dbContext.Entry(entitys);
            if (entry.State == EntityState.Detached)
            {
                entry.State = EntityState.Modified;
            }
            SaveChanges();
        }

        public bool Any(Expression<Func<T, bool>> @where)
        {
            return _dbSet.AsNoTracking().Any(@where);
        }

        public int Count()
        {
            return _dbSet.AsNoTracking().Count();
        }

        public int Count(Expression<Func<T, bool>> @where)
        {
            return _dbSet.AsNoTracking().Count(@where);
        }
        public async Task<T> FirstOrDefaultAsync(Expression<Func<T, bool>> @where)
        {
            return await _dbSet.AsNoTracking().FirstOrDefaultAsync(@where);
        }
        public T FirstOrDefault(Expression<Func<T, bool>> @where)
        {
            return _dbSet.AsNoTracking().FirstOrDefault(@where);
        }

        public T FirstOrDefault<TOrder>(Expression<Func<T, bool>> @where, Expression<Func<T, TOrder>> order, bool isDesc = false)
        {
            if (isDesc)
            {
                return this._dbSet.AsNoTracking().OrderByDescending(order).FirstOrDefault(@where);
            }
            else
            {
                return this._dbSet.AsNoTracking().OrderBy(order).FirstOrDefault(@where);
            }
        }

        public IQueryable<T> Distinct(Expression<Func<T, bool>> @where)
        {
            return this._dbSet.AsNoTracking().Where(@where).Distinct();

        }


        public IQueryable<T> Where(Expression<Func<T, bool>> @where)
        {
            return this._dbSet.Where(@where);
        }

        public IQueryable<T> Where<TOrder>(Expression<Func<T, bool>> @where, Expression<Func<T, TOrder>> order, bool isDesc = false)
        {
            if (isDesc)
            {
                return this._dbSet.Where(@where).OrderByDescending(order);
            }
            else
            {
                return this._dbSet.Where(@where).OrderBy(order);
            }
        }


        public IEnumerable<T> WherePage<TOrder>(Func<T, bool> @where, Func<T, TOrder> order, int pageIndex, int pageSize, out int count, bool isDesc)
        {
            count = Count();
            if (isDesc)
            {

                return _dbSet.Where(@where).OrderByDescending(order).Skip((pageIndex - 1) * pageSize).Take(pageSize);
            }
            else
            {
                return this._dbSet.Where(@where).OrderBy(order).Skip((pageIndex - 1) * pageSize).Take(pageSize);
            }
        }
        public async Task<IEnumerable<T>> WherePageAsync<TOrder>(Func<T, bool> @where, Func<T, TOrder> order, int pageIndex, int pageSize, bool isDesc)
        {
            if (isDesc)
            {
                return await Task.Run(() => _dbSet.Where(@where).OrderByDescending(order).Skip((pageIndex - 1) * pageSize).Take(pageSize));
            }
            else
            {
                return await Task.Run(() => _dbSet.Where(@where).OrderBy(order).Skip((pageIndex - 1) * pageSize).Take(pageSize));
            }
        }

        public IEnumerable<T> Where<TOrder>(Func<T, bool> @where, Func<T, TOrder> order, int pageIndex, int pageSize, out int count, bool isDesc = false)
        {
            count = Count();
            if (isDesc)
            {
                return this._dbSet.Where(@where).OrderByDescending(order).Skip((pageIndex - 1) * pageSize).Take(pageSize);
            }
            else
            {
                return this._dbSet.Where(@where).OrderBy(order).Skip((pageIndex - 1) * pageSize).Take(pageSize);
            }
        }

        public IQueryable<T> Where<TOrder>(Expression<Func<T, bool>> @where, Expression<Func<T, TOrder>> order, int pageIndex, int pageSize, out int count, bool isDesc = false)
        {
            count = Count();
            if (isDesc)
            {
                return this._dbSet.Where(@where).OrderByDescending(order).Skip((pageIndex - 1) * pageSize).Take(pageSize);
            }
            else
            {
                return this._dbSet.Where(@where).OrderBy(order).Skip((pageIndex - 1) * pageSize).Take(pageSize);
            }
        }

        public IQueryable<T> GetAll()
        {
            return _dbSet.AsNoTracking();
        }

        public IQueryable<T> GetAll<TOrder>(Expression<Func<T, TOrder>> order, bool isDesc = false)
        {
            if (isDesc)
            {
                return this._dbSet.AsNoTracking().OrderByDescending(order);
            }
            else
            {
                return this._dbSet.AsNoTracking().OrderBy(order);
            }
        }

        public T GetById<TType>(TType id)
        {
            return this._dbSet.Find(id);
        }
        public async Task<T> GetByIdAsync<TType>(TType id)
        {
            return await _dbSet.FindAsync(id);
        }


        public TType Max<TType>(Expression<Func<T, TType>> column)
        {
            if (this._dbSet.AsNoTracking().Any())
            {
                return this._dbSet.AsNoTracking().Max(column);
            }
            return default;
        }
        public async Task<TType> MinAsync<TType>(Expression<Func<T, TType>> column, Expression<Func<T, bool>> @where)
        {
            var result = await _dbContext.Set<T>()
                                          .Where(@where)
                                          .Select(column)
                                          .DefaultIfEmpty()
                                          .MinAsync();
            return result;
        }
        public TType Max<TType>(Expression<Func<T, TType>> column, Expression<Func<T, bool>> @where)
        {
            var result = _dbContext.Set<T>()
                                .Select(column)
                                .DefaultIfEmpty()
                                .Max();
            return result;
        }

        public TType Min<TType>(Expression<Func<T, TType>> column)
        {
            var result = _dbContext.Set<T>()
                                .Select(column)
                                .DefaultIfEmpty()
                                .Min();
            return result;
        }

        public TType Min<TType>(Expression<Func<T, TType>> column, Expression<Func<T, bool>> @where)
        {
            var result = _dbContext.Set<T>()
                                .Where(@where)
                                .Select(column)
                                .DefaultIfEmpty()
                                .Min();
            return result;
        }

        public TType Sum<TType>(Expression<Func<T, TType>> selector, Expression<Func<T, bool>> @where) where TType : new()
        {
            object result = 0;

            if (new TType().GetType() == typeof(decimal))
            {
                result = this._dbSet.AsNoTracking().Where(where).Sum(selector as Expression<Func<T, decimal>>);
            }
            if (new TType().GetType() == typeof(decimal?))
            {
                result = this._dbSet.AsNoTracking().Where(where).Sum(selector as Expression<Func<T, decimal?>>);
            }
            if (new TType().GetType() == typeof(double))
            {
                result = this._dbSet.AsNoTracking().Where(where).Sum(selector as Expression<Func<T, double>>);
            }
            if (new TType().GetType() == typeof(double?))
            {
                result = this._dbSet.AsNoTracking().Where(where).Sum(selector as Expression<Func<T, double?>>);
            }
            if (new TType().GetType() == typeof(float))
            {
                result = this._dbSet.AsNoTracking().Where(where).Sum(selector as Expression<Func<T, float>>);
            }
            if (new TType().GetType() == typeof(float?))
            {
                result = this._dbSet.AsNoTracking().Where(where).Sum(selector as Expression<Func<T, float?>>);
            }
            if (new TType().GetType() == typeof(int))
            {
                result = this._dbSet.AsNoTracking().Where(where).Sum(selector as Expression<Func<T, int>>);
            }
            if (new TType().GetType() == typeof(int?))
            {
                result = this._dbSet.AsNoTracking().Where(where).Sum(selector as Expression<Func<T, int?>>);
            }
            if (new TType().GetType() == typeof(long))
            {
                result = this._dbSet.AsNoTracking().Where(where).Sum(selector as Expression<Func<T, long>>);
            }
            if (new TType().GetType() == typeof(long?))
            {
                result = this._dbSet.AsNoTracking().Where(where).Sum(selector as Expression<Func<T, long?>>);
            }
            return (TType)result;
        }

        public void Dispose()
        {
            _dbContext.Dispose();
        }


        # region 插入数据

        /// <summary>
        /// 插入数据
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="isSaveChange"></param>
        /// <returns></returns>
        public bool Insert(T entity, bool isSaveChange = true)
        {
            _dbSet.Add(entity);
            if (isSaveChange)
            {
                return SaveChanges() > 0;
            }
            return false;
        }

        /// <summary>
        /// 异步插入
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="isSaveChange"></param>
        /// <returns></returns>
        public async Task<bool> InsertAsync(T entity, bool isSaveChange = true)
        {
            _dbSet.Add(entity);
            if (isSaveChange)
            {
                return await SaveChangesAsync() > 0;
            }
            return false;
        }


        public bool Insert(List<T> entitys, bool isSaveChange = true)
        {
            _dbSet.AddRange(entitys);
            if (isSaveChange)
            {
                return SaveChanges() > 0;
            }
            return false;
        }

        public async Task<bool> InsertAsync(List<T> entitys, bool isSaveChange = true)
        {
            _dbSet.AddRange(entitys);
            if (isSaveChange)
            {
                return await SaveChangesAsync() > 0;
            }
            return false;
        }
        #endregion

        #region 删除
        public bool Delete(List<T> entitys, bool isSaveChange = true)
        {
            entitys.ForEach(entity =>
            {
                _dbSet.Attach(entity);
                _dbSet.Remove(entity);
            });
            return isSaveChange && SaveChanges() > 0;
        }

        public virtual async Task<bool> DeleteAsync(T entity, bool isSaveChange = true)
        {
            _dbSet.Attach(entity);
            _dbSet.Remove(entity);
            return isSaveChange && await SaveChangesAsync() > 0;
        }
        public virtual async Task<bool> DeleteAsync(List<T> entitys, bool isSaveChange = true)
        {
            entitys.ForEach(entity =>
            {
                _dbSet.Attach(entity);
                _dbSet.Remove(entity);
            });
            return isSaveChange && await SaveChangesAsync() > 0;
        }
        #endregion

        #region 更新数据
        public bool Update(T entity, bool isSaveChange = true, List<string> updatePropertyList = null)
        {
            if (entity == null)
            {
                return false;
            }
            _dbSet.Attach(entity);
            var entry = _dbContext.Entry(entity);
            if (updatePropertyList == null)
            {
                entry.State = EntityState.Modified;//全字段更新
            }
            else
            {

                updatePropertyList.ForEach(c =>
                {
                    entry.Property(c).IsModified = true; //部分字段更新的写法
                });


            }
            if (isSaveChange)
            {
                return SaveChanges() > 0;
            }
            return false;
        }
        public bool Update(List<T> entitys, bool isSaveChange = true)
        {
            if (entitys == null || entitys.Count == 0)
            {
                return false;
            }
            entitys.ForEach(c =>
            {
                Update(c, false);
            });
            if (isSaveChange)
            {
                return SaveChanges() > 0;
            }
            return false;
        }
        public async Task<bool> UpdateAsync(T entity, bool isSaveChange, List<string> updatePropertyList)
        {
            if (entity == null)
            {
                return false;
            }
            _dbSet.Attach(entity);
            var entry = _dbContext.Entry<T>(entity);
            if (updatePropertyList == null)
            {
                entry.State = EntityState.Modified;//全字段更新
            }
            else
            {
                updatePropertyList.ForEach(c =>
                {
                    entry.Property(c).IsModified = true; //部分字段更新的写法
                });

            }
            if (isSaveChange)
            {
                return await SaveChangesAsync() > 0;
            }
            return false;
        }
        public async Task<bool> UpdateAsync(List<T> entitys, bool isSaveChange = true)
        {
            if (entitys == null || entitys.Count == 0)
            {
                return false;
            }
            entitys.ForEach(c =>
            {
                _dbSet.Attach(c);
                _dbContext.Entry(c).State = EntityState.Modified;
            });
            if (isSaveChange)
            {
                return await SaveChangesAsync() > 0;
            }
            return false;
        }


        #endregion

        #region SQL语句

        // [Obsolete]
        //public int ExecuteSql(string sql)
        //{
        //    return _dbContext.Database.ExecuteSqlCommand(sql);
        //}

        //[Obsolete]
        public List<T> ExecuteSql(string sql)
        {
            return _dbSet.FromSqlRaw(sql).ToList();
        }

        /// <summary>
        /// 用于查询
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="spList"></param>
        /// <returns></returns>
        public List<T> FromSqlRaw(string sql, List<DbParameter> spList)
        {

            return _dbSet.FromSqlRaw(sql, spList.ToArray()).ToList();
        }
        public async Task<List<T>> FromSqlRawAsync(string sql, List<DbParameter> spList)
        {
            return await _dbSet.FromSqlRaw(sql, spList.ToArray()).ToListAsync();
        }

        /// <summary>
        /// 执行SQL语句返回的条数，用于增删改
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="spList"></param>
        /// <returns></returns>
        public async Task<int> ExecuteSqlAsync(string sql, List<DbParameter> spList)
        {
            return await _dbContext.Database.ExecuteSqlRawAsync(sql, spList.ToArray());
        }
        public int ExecuteSql(string sql, List<DbParameter> spList)
        {
            return _dbContext.Database.ExecuteSqlRaw(sql, spList.ToArray());
        }
















        public virtual DataTable GetDataTableWithSql(string sql, List<DbParameter> spList)
        {

            throw new NotImplementedException();
        }



        public async Task<List<T>> GetAllAsync()
        {
            return await _dbSet.AsNoTracking().ToListAsync();
        }

        public async Task<bool> UpdateAsync1(T entity, bool isSaveChange, string updatePropert)
        {
            if (entity == null)
            {
                return false;
            }
            _dbSet.Attach(entity);
            var entry = _dbContext.Entry(entity);
            if (updatePropert == null)
            {
                entry.State = EntityState.Modified;//全字段更新
            }
            else
            {
                entry.Property(updatePropert).IsModified = true; //部分字段更新的写法
            }
            if (isSaveChange)
            {
                return await SaveChangesAsync() > 0;
            }
            return false;
        }

        public async Task<int> CountAsync()
        {
            return await _dbSet.AsNoTracking().CountAsync();
        }

        public async Task<int> CountAsync(Expression<Func<T, bool>> where)
        {
            return await _dbSet.AsNoTracking().CountAsync(@where);
        }

        public DataTable GetDataTableWithSql(string sql)
        {
            throw new NotImplementedException();
        }

        #endregion

    }

}
